CLASS lhc_ymoon_i_vbak DEFINITION INHERITING FROM cl_abap_behavior_handler.
  PRIVATE SECTION.

    METHODS get_instance_authorizations FOR INSTANCE AUTHORIZATION
      IMPORTING keys REQUEST requested_authorizations FOR ymoon_i_vbak RESULT result.

    METHODS create_so_api FOR DETERMINE ON SAVE
      IMPORTING keys FOR ymoon_i_vbak~create_so_api.

    TYPES:
      "스탠다드 API Response Information
      BEGIN OF post_result,
        post_body   TYPE string,
        post_status TYPE string,
      END OF post_result.

    CONSTANTS:
      c_scenario TYPE string VALUE 'YMOON_CS_VBAK',
      c_service  TYPE string VALUE 'YMOON_OS_SALESORDER_REST'.

    DATA:http_client TYPE REF TO ymoon_api.

    "API 통신을 위해 생성한 함수
    METHODS:
      create_order
        IMPORTING params        TYPE sysuuid_x16
        RETURNING VALUE(result) TYPE post_result
        RAISING   cx_static_check.


ENDCLASS.

CLASS lhc_ymoon_i_vbak IMPLEMENTATION.

  METHOD get_instance_authorizations.
  ENDMETHOD.

  METHOD create_so_api.
    DATA : lt_sales_order TYPE TABLE FOR UPDATE ymoon_i_vbak,
           ls_sales_order TYPE STRUCTURE FOR UPDATE ymoon_i_vbak.

    " CBO 데이터 조회
    READ ENTITIES OF ymoon_i_vbak IN LOCAL MODE
         ENTITY ymoon_i_vbak
         ALL FIELDS
           " keys 값 설정
         WITH CORRESPONDING #( keys )
         RESULT DATA(lt_sales_order_result)
      " TODO: variable is assigned but never used (ABAP cleaner)
         FAILED    DATA(lt_failed)
         " TODO: variable is assigned but never used (ABAP cleaner)
         REPORTED  DATA(lt_reported).

    " Standard API 호출
    DATA(key) = keys[ 1 ].

    " cbo에서 조회한 데이터로 standard api 호출
    DATA(result) = me->create_order( key-orderuuid ).

    " 호출 후 결과 값 확인
    DATA result_msg    TYPE string.
    DATA order_id      TYPE string.
    DATA result_status TYPE string.

    result_status = result-post_status.
    result_msg    = result-post_body.

    DATA:abap_msg TYPE REF TO data.
    DATA:ab_msg TYPE REF TO data.

    /ui2/cl_json=>deserialize( EXPORTING json = result_msg CHANGING data = abap_msg ).

    FIELD-SYMBOLS:<fs_msg>        TYPE any,
                  <fs_line>       TYPE any,
                  <fs_salesorder> TYPE any,
                  <fs_error>      TYPE any,
                  <fs_result_msg> TYPE any.

    ASSIGN abap_msg->* TO <fs_msg>.
    ASSIGN ('<fs_msg>-d->*') TO <fs_line>.
    ASSIGN ('<fs_line>-salesorder->*') TO <fs_salesorder>.

    IF <fs_salesorder> IS ASSIGNED.
      order_id = <fs_salesorder>.
      result_msg = 'Success'.

    ELSE.
      ASSIGN ('<fs_msg>-error->*') TO <fs_error>.
      ASSIGN ('<fs_error>-message->*') TO <fs_line>.
      ASSIGN ('<fs_line>-value->*') TO <fs_result_msg>.
      IF <fs_result_msg> IS ASSIGNED.
        result_msg = <fs_result_msg>.
      ELSE.
      ENDIF.
    ENDIF.



    LOOP AT lt_sales_order_result INTO DATA(sales_order_read).
      ls_sales_order             = CORRESPONDING #( sales_order_read ).
      ls_sales_order-zsalesorder = order_id.
      ls_sales_order-ifmsg       = result_msg.
      ls_sales_order-ifstatus    = result_status.

      APPEND ls_sales_order TO lt_sales_order.
    ENDLOOP.

    " CBO 데이터 업데이트
    MODIFY ENTITIES OF ymoon_i_vbak IN LOCAL MODE
           ENTITY ymoon_i_vbak UPDATE SET FIELDS WITH lt_sales_order
           " TODO: variable is assigned but never used (ABAP cleaner)
           MAPPED   DATA(ls_mapped_modify)
           " TODO: variable is assigned but never used (ABAP cleaner)
           FAILED   DATA(lt_failed_modify)
           " TODO: variable is assigned but never used (ABAP cleaner)
           REPORTED DATA(lt_reported_modify).
  ENDMETHOD.



  "POST
  METHOD create_order.
    CREATE OBJECT me->http_client
      EXPORTING
        i_scenario     = c_scenario
        i_service      = c_service
      EXCEPTIONS
        no_arrangement = 1.

    IF sy-subrc = 1.
      result-post_body    = 'no_arrangement:' && c_scenario.
      result-post_status  = 400.
    ENDIF.
    CHECK sy-subrc <> 1.

    "Order UUID 기준으로 데이터 조회
    READ ENTITIES OF ymoon_i_vbak IN LOCAL MODE
        ENTITY ymoon_i_vbak
        ALL FIELDS WITH VALUE #( ( orderuuid = params ) )
        RESULT DATA(lt_sales_order_result)
        "Item 조회
        ENTITY ymoon_i_vbak BY \_item
        ALL FIELDS WITH VALUE #( ( orderuuid = params ) )
        RESULT DATA(lt_sales_order_item_result)
        "partner 조회
        ENTITY ymoon_i_vbak BY \_partner
        ALL FIELDS WITH VALUE #( ( orderuuid = params ) )
        RESULT DATA(lt_sales_order_partner_result).

    "Item Body
    DATA : item_json TYPE string.
    LOOP AT lt_sales_order_item_result INTO DATA(sales_order_item).
      IF ( item_json <> '' ).
        item_json = item_json && ',{'.
      ENDIF.

      item_json = item_json && '"SalesOrderItem":"' && sales_order_item-salesorderitem && '",' &&
                               '"Material":"' && sales_order_item-material && '",' &&
                               '"RequestedQuantity":"' && sales_order_item-requestedquantity && '",' &&
                               '"RequestedQuantityUnit":"' && sales_order_item-requestedquantityunit && '"' &&
                               '}'.
    ENDLOOP.

    "Partner Body
    DATA : partner_json TYPE string.
    LOOP AT lt_sales_order_partner_result INTO DATA(sales_order_partner).
      IF ( partner_json <> '' ).
        partner_json = partner_json && ',{'.
      ENDIF.

      partner_json = partner_json && '"PartnerFunction":"' && sales_order_partner-partnerfunction && '",' &&
                                     '"Customer":"' && sales_order_partner-customer && '"' &&
                                     '}'.
    ENDLOOP.

    "날짜 Type을 YYYY-MM-DD로 바꿔야 해서 가공
    DATA(sales_order_header) = lt_sales_order_result[ 1 ].

    "Pricing Body
    DATA : pricing_json TYPE string.
    pricing_json = pricing_json && '"ConditionType":"' && sales_order_header-conditiontype && '",' &&
                                   '"ConditionRateValue":"' && sales_order_header-conditionratevalue && '",' &&
                                   '"ConditionCurrency":"' && sales_order_header-conditioncurrency && '"' &&
                                   '}'.

    DATA(deliveryyear)  = substring( val = sales_order_header-requesteddeliverydate len = 4 ).
    DATA(deliverymonth) = substring( val = sales_order_header-requesteddeliverydate off = 4 len = 2 ).
    DATA(deliveryday)   = substring( val = sales_order_header-requesteddeliverydate off = 6 len = 2 ).

    DATA(orderyear)  = substring( val = sales_order_header-customerpurchaseorderdate len = 4 ).
    DATA(ordermonth) = substring( val = sales_order_header-customerpurchaseorderdate off = 4 len = 2 ).
    DATA(orderdday)  = substring( val = sales_order_header-customerpurchaseorderdate off = 6 len = 2 ).

    DATA(salesyear)  = substring( val = sales_order_header-salesorderdate len = 4 ).
    DATA(salesmonth) = substring( val = sales_order_header-salesorderdate off = 4 len = 2 ).
    DATA(salesday)   = substring( val = sales_order_header-salesorderdate off = 6 len = 2 ).

    " post할 데이터 가공
    DATA(json) =
        '{' &&
        ' "SenderBusinessSystemName":"' && sales_order_header-senderbusinesssystemname && '",' &&
        ' "PurchaseOrderByCustomer":"' && sales_order_header-purchaseorderbycustomer && '",' &&
        ' "SalesOrderType":"' && sales_order_header-salesordertype && '",' &&
        ' "SalesOrganization":"' && sales_order_header-salesorganization && '",' &&
        ' "DistributionChannel":"' && sales_order_header-distributionchannel && '",' &&
        ' "SoldToParty":"' && sales_order_header-soldtoparty && '",' &&
        "' "RequestedDeliveryDate":"' && DeliveryYear && '-' && Deliverymonth && '-' && Deliveryday && '",' && "오류용 주석
        ' "RequestedDeliveryDate":"' && deliveryyear && '-' && deliverymonth && '-' && deliveryday && 'T00:00:00' && '",' &&
        ' "CustomerPurchaseOrderDate":"' && orderyear && '-' && ordermonth && '-' && orderdday && 'T00:00:00' && '",' &&
        ' "SalesOrderDate":"' && salesyear && '-' && salesmonth && '-' && salesday && 'T00:00:00'  && '",' &&
        ' "to_Item":{' &&
        '  "results":[{' &&
        '  ' && item_json &&
        '  ]' &&
        ' },' &&
        ' "to_Partner":{' &&
        '  "results":[{' &&
        '  ' && partner_json &&
        '  ]' &&
        ' },' &&
        ' "to_PricingElement":{' &&
        '  "results":[{' &&
        '  ' && pricing_json &&
        '  ]' &&
        ' }' &&
        '}'.

    DATA(token) = me->http_client->get_token_cookies( ).
    IF token IS NOT INITIAL.

      me->http_client->post(
        EXPORTING
          json   = json
        IMPORTING
          body   = DATA(body)
          status = DATA(status)
      ).
      result-post_body    = body.
      result-post_status  = status.
    ELSE.
      result-post_body    = 'Get Token Error'.
      result-post_status  = 400.
    ENDIF.


  ENDMETHOD.

ENDCLASS.

CLASS lsc_ymoon_i_vbak DEFINITION INHERITING FROM cl_abap_behavior_saver.
  PROTECTED SECTION.

    METHODS save_modified REDEFINITION.

    METHODS cleanup_finalize REDEFINITION.

ENDCLASS.

CLASS lsc_ymoon_i_vbak IMPLEMENTATION.

  METHOD save_modified.
  ENDMETHOD.

  METHOD cleanup_finalize.
  ENDMETHOD.

ENDCLASS.
